const router = require('express').Router()
const { to } = require('await-to-js')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const Bee = require('../../../common/bee/bee')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const SECRET_KEY = require('../../../common/SECRET_KEY')

router.post('/login', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  const { account, pwd } = req.body

  // 参数错误处理
  if (!Bee.StringUtils.isUsername(account) || !Bee.StringUtils.isPassword(pwd))
    return handleError(10003)

  const [findUserError, findUser] = await to(
    db.query(
      'SELECT * FROM users u INNER JOIN userinfo ui ON u.id = ui.id WHERE u.account=?',
      [account]
    )
  )
  // 错误处理
  if (findUserError || !findUser) return handleError(-1, findUserError)
  // 用户名错误
  if (findUser.length !== 1) return handleError(60011)
  const user = findUser[0]
  // 解密
  const PasswordValid = bcrypt.compare(pwd, user.pwd)
  const [passwordValidError, isPasswordValid] = await to(PasswordValid)
  // 密码错误处理
  if (passwordValidError || !isPasswordValid)
    return handleError(60014, passwordValidError)

  // 密码正确
  // 生成 token 将用户的唯一标识 id 作为第一个参数
  // SECRET_KEY 作为取得用户 id 密匙
  const token = jwt.sign(
    {
      id: user.id,
      account: user.account,
      created_time: user.created_time,
      status: user.status,
      info_updated_time: user.info_updated_time,
      username: user.username,
      sex: user.sex,
      about: user.about,
      avatar_url: user.avatar_url,
      tel: user.tel,
      last_login_ip: user.last_login_ip,
      last_login_time: user.last_login_time,
      login_num: user.login_num,
      mail: user.mail,
    },
    SECRET_KEY,
    {
      // expiresIn: '2h'
    }
  )

  // 更新用户登录信息
  // 客户端ip
  // const clientIp = req.ip.match(/\d+\.\d+\.\d+\.\d+/)[0]

  const [updatedUserInfoError, updatedUserInfo] = await to(
    db.query(
      'UPDATE userinfo SET last_login_time = NOW(), last_login_ip = ?, login_num = login_num + 1 WHERE id=?',
      ['', user.id]
    )
  )
  if (updatedUserInfoError || !updatedUserInfo)
    return handleError(-1, updatedUserInfoError)

  // 响应
  resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      token,
      user: {
        id: user.id,
        account: user.account,
        created_time: user.created_time,
        status: user.status,
        info_updated_time: user.info_updated_time,
        username: user.username,
        sex: user.sex,
        about: user.about,
        avatar_url: user.avatar_url,
        tel: user.tel,
        last_login_ip: user.last_login_ip,
        last_login_time: user.last_login_time,
        login_num: user.login_num,
        mail: user.mail,
      },
    },
  })
})

module.exports = router
